<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" @submit.native.prevent>
      <el-form-item :label="$t('video.list.whether-to-review')" prop="status">
        <dict-select :options="dict.type.video_audit_type" v-model="queryParams.status"
          :placeholder="$t('video.list.please-choose-whether-to-review')" clearable />
      </el-form-item>
      <el-form-item :label="$t('title')" prop="title">
        <el-input v-model="queryParams.title" :placeholder="$t('video.list.please-enter-a-title')" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('search') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('reset') }}</el-button>
        <el-button type="primary" plain size="mini" @click="handleAdd" v-hasPermi="['video:list:add']">{{
          $t('video.list.add-short-video') }}
        </el-button>
        <el-button type="danger" :disabled="checkList.length == 0" plain size="mini" @click="handleAllRemove"
          v-hasPermi="['video:list:remove']">{{ $t('video.list.batch-deletion') }}
        </el-button>
        <el-button type="success" :disabled="disabledCanAllAudit" plain size="mini" @click="handleAudit(checkList, 1)"
          v-hasPermi="['video:list:audit']">{{ $t('video.list.batch-review') }}
        </el-button>
      </el-form-item>
    </el-form>

    <empty-content :show="!!(videoList && videoList.length)">
      <el-checkbox-group class="video-list-wrapper" v-model="checkList" v-for="(video, index) in videoList" :key="index">
        <!--        <el-col :xs="24" :lg="6" :md="8" :sm="12" v-for="(video,index) in videoList" :key="index"-->
        <!--                class="video-list-wrapper">-->
        <el-checkbox class="video-list-checkbox" :label="video.id"></el-checkbox>
        <el-card>
          <!--          <video-->
          <!--            class="video-list-preview"-->
          <!--            style="object-fit:cover;"-->
          <!--            preload="none"-->
          <!--            :poster="$yun.getPreviewUrl(video.img)"-->
          <!--            :src="$yun.getPreviewUrl(video.url)"-->
          <!--            controls="controls">-->
          <!--            {{ $t('video.list.please-upgrade-your-browser') }}-->
          <!--          </video>-->
          <div class="video-img-box">
            <preview-video-img img-style="height:179px" :video-url="video.url"></preview-video-img>
          </div>
          <el-descriptions title="" :column="2" class="video-list-description">
            <el-descriptions-item :label="$t('title')" span="2" contentStyle="width:calc(100% - 44px)">
              <over-flow-tip :text="video.title" />
            </el-descriptions-item>
            <el-descriptions-item label="审核人" :labelStyle="{ lineHeight: 2 }" span="2">
              <span style="line-height: 2.1">{{video.auditUser}}</span>
            </el-descriptions-item>
            <el-descriptions-item label="审核状态" :labelStyle="{ lineHeight: 2 }" span="2">
              <dict-tag :options="dict.type.video_audit_type" :value="video.status" />
            </el-descriptions-item>
            <el-descriptions-item :label="$t('video.list.sort')">{{ video.sort }}</el-descriptions-item>
            <el-descriptions-item :label="$t('video.list.number-of-likes')">{{ video.likeCount }}
            </el-descriptions-item>
            <el-descriptions-item :label="$t('video.list.favorites')">{{ video.collection }}</el-descriptions-item>
            <el-descriptions-item :label="$t('video.list.views')">{{ video.watch }}</el-descriptions-item>
            <el-descriptions-item label="标签" style="white-space: nowrap">
              <div style="display: flex;flex-wrap: wrap">
                <el-tag type="info" v-for="(item,index) in video.shortVideoCategoryName" :key="index" style="margin-left: 10px;margin-bottom: 6px">{{item}}</el-tag>
              </div>
            </el-descriptions-item>
          </el-descriptions>
          <div class="video-list-footer" style="display: flex;justify-content: space-between;align-items: center">
            <div>
              <el-button size="mini" type="primary" @click="handleUpdate(video)">{{ $t('edit') }}</el-button>
              <el-button size="mini" type="primary" @click="$router.push(`/video/comments?id=${video.id}`)">
                {{ $t('video.list.view-comments') }}
              </el-button>
              <el-button size="mini" type="danger" @click="handleDelete([video.id])">{{ $t('delete') }}</el-button>
            </div>
            <div style="display: inline-block;" v-show="video.status == 0">
              <el-button type="text" @click="handleAudit(video.id,2)">审核</el-button>
            </div>
<!--            <el-dropdown v-if="video.status == '0'" trigger="click" style="float: right" placement="top-start">-->
<!--              <el-button size="mini" type="text" icon="el-icon-d-arrow-right">{{ $t('audit') }}</el-button>-->
<!--              <el-dropdown-menu slot="dropdown">-->
<!--                <el-dropdown-item>-->
<!--                  <div @click="handleAudit([video.id], 1)">{{ $t('pass') }}</div>-->
<!--                </el-dropdown-item>-->
<!--                <el-dropdown-item>-->
<!--                  <div @click="handleAudit([video.id], 2)">不通过</div>-->
<!--                </el-dropdown-item>-->
<!--              </el-dropdown-menu>-->
<!--            </el-dropdown>-->


            <!--            <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"-->
            <!--                         v-hasPermi="['monitor:job:changeStatus', 'monitor:job:query']">-->
            <!--              <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>-->
            <!--              <el-dropdown-menu slot="dropdown">-->
            <!--                <el-dropdown-item command="handleFund">用户资金</el-dropdown-item>-->
            <!--                <el-dropdown-item v-if="scope.row.source == dict.type.user_source[0].value" command="setWater">-->
            <!--                  设置水军-->
            <!--                </el-dropdown-item>-->
            <!--                <el-dropdown-item v-else command="cancelWater">取消为水军</el-dropdown-item>-->
            <!--                <el-dropdown-item command="handleAmount">修改余额</el-dropdown-item>-->
            <!--              </el-dropdown-menu>-->
            <!--            </el-dropdown>-->
          </div>
        </el-card>
        <!--        </el-col>-->
      </el-checkbox-group>
    </empty-content>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改汇率对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item :label="$t('title')" prop="title">
          <el-input v-model="form.title" :placeholder="$t('video.list.please-enter-the-short-video-title')" />
        </el-form-item>

        <el-form-item :label="$t('user')" prop="userId" v-if="isAdd">
          <remote-select v-model="form.userId" :remote-api="remoteUser" search-key="userName" value-key="id"
            label-key="userName" :placeholder="$t('video.list.please-select-a-user')" :init-data="initUserData" />
        </el-form-item>

        <el-form-item label="分类标签" prop="shortVideoCategoryId">
          <remote-select v-model="form.shortVideoCategoryId" :remote-api="remoteCategory" search-key="tagName"
            value-key="tagCode" label-key="tagName" :multiple="true"
            :placeholder="$t('video.list.please-select-a-short-video-category')" :init-data="initCategoryData"
            :dataFormatter="(rsp) => { return rsp.data }" />
        </el-form-item>
        <el-form-item :label="$t('video.list.sort')" prop="sort">
          <el-input-number :min="0" v-model="form.sort" :placeholder="$t('video.list.please-enter-the-sort')" />
        </el-form-item>
        <el-form-item :label="$t('video.list.video')" prop="url">
          <FileUpload :limit="1" :fileType="['mp4']" :file-size="100" v-model="form.url"></FileUpload>
        </el-form-item>
        <el-form-item :label="$t('video.list.number-of-likes')" prop="likeCount">
          <el-input-number :min="0" v-model="form.likeCount" placeholder="请输入点赞数" />
        </el-form-item>
        <el-form-item :label="$t('video.list.favorites')" prop="collection">
          <el-input-number :min="0" v-model="form.collection" placeholder="请输入收藏数" />
        </el-form-item>
        <el-form-item :label="$t('video.list.views')" prop="watch">
          <el-input-number :min="0" v-model="form.watch" placeholder="请输入播放数" />
        </el-form-item>
        <el-form-item :label="$t('video.list.show')" prop="show">
          <dict-select dict-type="boolean_value" v-model="form.show" type="radio" />
        </el-form-item>
        <el-form-item :label="$t('video.list.details-description')" prop="detail">
          <el-input type="textarea" :rows="3" v-model="form.detail"
            :placeholder="$t('video.list.please-enter-details')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('ok') }}</el-button>
        <el-button @click="cancel">{{ $t('cancel') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog title="设置短视频标签" :visible.sync="openSelectLable" width="500px" append-to-body>
      <el-form ref="formAutit" :model="formAudit">
        <el-form-item label="审批" prop="radio" :rules="[{required: true,message: '审批状态不能为空',trigger: 'blur'}]">
          <el-radio v-model="formAudit.radio" label="1">通过</el-radio>
          <el-radio v-model="formAudit.radio" label="2">不通过</el-radio>
        </el-form-item>
        <!-- <el-form-item label="短视频标签" prop="tagIds" :rules="[{required: true,message: '短视频标签不能为空',trigger: 'blur'}]">
          <el-select v-model="formAudit.tagIds" multiple>
            <el-option v-for="(item, index) in allCategoryData" :key="index" :label="item.tagName" :value="item.tagCode">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="奖励金额" prop="bonus" :rules="[{required: true,message: '奖励金额不能为空',trigger: 'blur'}]">
          <el-input type="number" :rows="3" v-model="formAudit.bonus"
                    placeholder="请输入奖励金额" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormAudit()">确定</el-button>
        <el-button @click="cancelAudit">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import DictSelect from "@/components/DictSelect/index.vue";
import { addVideo, auditVideo, editVideo, listVideo, removeVideo } from "@/api/video/list";
import VideoCategory from "@/views/video/category/index.vue";
import router from "@/router";
import { listCategory } from "@/api/video/category";
import RemoteSelect from "@/components/RemoteSelect/index.vue";
import { listList } from "@/api/user/list";
import OverFlowTip from "@/components/OverFlowTip/index.vue";
import EmptyContent from "@/components/EmptyContent/index.vue";
import FileUpload from "@/components/FileUpload/index.vue";
import PreviewVideoImg from "@/components/PreviewVideoImg/index.vue";

export default {
  name: "VideoList",
  dicts: ['boolean_value', 'video_audit_type'],
  components: { PreviewVideoImg, EmptyContent, OverFlowTip, RemoteSelect, VideoCategory, DictSelect, FileUpload },
  data() {
    return {
      playIcon: false,
      showSearch: true,
      total: 0,
      videoList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null
      },
      title: "",
      // 是否显示弹出层
      open: false,
      form: {
        show: 1,
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: this.$t('can-not-empty', [this.$t('title')]), trigger: "blur" }
        ],
        url: [
          { required: true, message: this.$t('please-upload', [this.$t('short-video')]), trigger: "change" }
        ],
        img: [
          { required: true, message: this.$t('please-upload', [this.$t('video.list.cover-picture')]), trigger: "change" }
        ],
        userId: [
          { required: true, message: this.$t('please-select', [this.$t('user')]), trigger: "change" }
        ],
        shortVideoCategoryId: [
          { required: true, message: this.$t('please-select', [this.$t('classification')]), trigger: "blur" }
        ],
      },
      remoteCategoryOptions: [],
      remoteCategoryLoading: false,
      initCategoryData: [],
      initUserData: [],
      checkList: [],
      isAdd: null,
      openSelectLable: false,
      allCategoryData: [],
      formAudit: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    router() {
      return router
    },
    getList() {
      this.loading = true;
      //重制选择框
      this.checkList = []
      // this.videoList = [{
      //   "id": 1,
      //   "show": "0",
      //   "sort": 1,
      //   "likeCount": 1,
      //   "collection": 2,
      //   shortVideoCategoryId: 1,
      //   "watch": 3,
      //   status: 0,
      //   "title": "dwada",
      //   "url": "http://localhost:1024/dev-api/profile/upload/2023/05/17/2022-07-02 10.42.36_20230517172508A003.mp4",
      //   "img": "http://localhost:1024/dev-api/profile/upload/2023/05/17/11486_20230517172718A005.png",
      //   "detail": "dwada"
      // },
      //   {
      //     "id": 2,
      //     "show": "0",
      //     "sort": 1,
      //     "likeCount": 1,
      //     "collection": 2,
      //     shortVideoCategoryId: 1,
      //     "watch": 3,
      //     status: 1,
      //     "title": "dwada",
      //     "url": "http://localhost:1024/dev-api/profile/upload/2023/05/17/2022-07-02 10.42.36_20230517172508A003.mp4",
      //     "img": "http://localhost:1024/dev-api/profile/upload/2023/05/17/11486_20230517172718A005.png",
      //     "detail": "dwada"
      //   }
      // ];
      // this.total = 1;
      // this.loading = false;
      // return
      listVideo(this.queryParams).then(response => {
        this.videoList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //删除
    handleDelete(ids) {
      this.$modal.confirm(this.$t('video.list.are-you-sure-to-delete-this-video')).then(function () {
        return removeVideo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('delete-success'));
      }).catch(() => {
      });
    },
    handleAdd() {
      this.isAdd = true
      this.reset();
      Promise.all([listList({ pageSize: 20, pageNum: 1 }), listCategory()]).then(datas => {
        this.initUserData = datas[0].data.records;
        this.initCategoryData = datas[1].data
        this.open = true;
        this.title = '添加短视频';
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const data = {
            ...this.form,
            show: Number(this.form.show)
          }
          if (this.form.id != null) {
            editVideo(data).then(response => {
              this.$modal.msgSuccess(this.$t('edit-success'));
              this.open = false;
              this.getList();
            });
          } else {
            addVideo(data).then(response => {
              this.$modal.msgSuccess(this.$t('add-success'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        show: 1
      };
      this.resetForm("form");
    },
    remoteCategory: listCategory,
    remoteUser: listList,
    handleUpdate(video) {
      this.isAdd = false
      this.reset();
      listCategory({ pageNum: 1, pageSize: 10, id: video.shortVideoCategoryId }).then(rsp => {
        this.initCategoryData = rsp.data
        this.form = { ...video, show: video.show ? '1' : '0' };
        this.open = true;
        this.title = this.$t('edit');
      })
    },
    async handleAudit(id, status) {
      if(status === 2) this.checkList = [id]
      listCategory().then(rqs => {
        this.allCategoryData = rqs.data;
        this.openSelectLable = true;
      })
      /* if (status == 1) {//通过
        this.formAudit = { ids: id, status: status };
        listCategory().then(rqs => {
          this.allCategoryData = rqs.data;
          this.openSelectLable = true;
        })
      } else {//拒绝
        await this.$modal.confirm(`是否审核不通过选中视频？`)
        await auditVideo({ ids: id, status: status })
        this.$modal.msgSuccess("审核成功！");
        this.getList();
      } */
    },
    async auditFun(id, status) {
      await this.$modal.confirm(`是否审核${status - 1 ? '不' : ''}通过选中视频？`)
      await auditVideo(id, status)
      this.$modal.msgSuccess(this.$t('audit-success'));
      this.getList();
    },
    async handleAllRemove() {
      if (this.checkList.length) {
        this.handleDelete(this.checkList)
      }
    },
    async handleAllAudit() {
      if (this.checkList.length) {
        this.$confirm(this.$t('video.list.batch-review-selected-short-videos'), this.$t('video.list.batch-review'), {
          distinguishCancelAndClose: true,
          confirmButtonText: this.$t('pass'),
          cancelButtonText: this.$t('reject'),
        }).then(() => {
          this.handleAudit(this.checkList, 1)
        })
          .catch(action => {
            if (action == 'cancel') this.handleAudit(this.checkList, 2)
          });
      }
    },
    submitFormAudit: function () {
      this.$refs["formAutit"].validate(valid => {
        if (valid) {
          if(this.formAudit.ids) this.checkList.push(this.formAudit.ids[0])
          this.checkList = Array.from(new Set(this.checkList))
          this.formAudit.status = this.formAudit.radio
          delete this.formAudit.radio
          let obj = {
            ...this.formAudit,
            ids:this.checkList,
          }
          auditVideo(obj).then(rqs => {
            this.openSelectLable = false;
            this.$modal.msgSuccess("审核成功！");
            this.getList();
          })
        }
      })
    },
    cancelAudit: function () {
      this.openSelectLable = false;
      this.formAudit = {};
    },
  },
  computed: {
    disabledCanAllAudit() {
      if (this.checkList && this.checkList.length && this.videoList && this.videoList.length) {
        console.log(this.videoList)
        return this.videoList.some(video => {
          //已审核但是在批量选中中
          return video.status != '0' && this.checkList.includes(video.id);
        })
      }
      return true
    }
  }
};
</script>

<style lang="scss" scoped>

.video-list-preview {
  width: 100%;
  height: 200px;
}

.video-list-description {
  padding-top: 20px;
  height: 305px;
}

.video-list-footer {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid rgba(0, 0, 0, .125);
}

.video-list-wrapper {
  display: inline-block;
  margin-bottom: 38px;
  position: relative;
  margin-right: 20px;
  width: 360px;

  .el-card {
    width: 100%;
  }
}

.video-list-checkbox {
  position: absolute;
  top: 6px;
  right: 5px;

  .el-checkbox__label {
    display: none;
  }
}
.video-img-box {
  margin-top: 10px;
  height: 179px;
}

::v-deep .el-checkbox__label {
  display: none;
}
</style>
